﻿using System;
using System.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using Me.Amon.Da.Db;
using Me.Amon.Da.Db.OMS;
using Me.Amon.POS.C;
using Me.Amon.Util;

namespace Me.Amon.POS
{
    public partial class UpdateInv : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            var user = WebUtil.CurrentUser(Session);
            if (user.Rank < IUser.LEVEL_01)
            {
                Response.Redirect(IEnv.HOME_PAGE);
                return;
            }

            var dba = new RDBEngine();

            var spu = Request["spu"];
            if (!CharUtil.IsValidateHash(spu))
            {
                return;
            }

            ReadSpu(dba, spu);

            dba.Reset();
            ListInv(dba, spu, 0);
        }

        #region 事件处理
        protected void TbCode_TextChanged(object sender, EventArgs e)
        {
            var dba = new RDBEngine();
            FindSpu(dba, TbCode.Text);

            dba.Reset();
            ListInv(dba, HdId.Value, 0);
        }

        protected void BtUpdate_Click(object sender, EventArgs e)
        {
            var dba = new RDBEngine();
            SaveSpu(dba);

            dba.Reset();
            ListInv(dba, HdId.Value, 0);

            TbAdjust.Text = "0";
            TbAdjust.Focus();
        }

        protected void BtCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/POS/Spus.aspx?cat=" + HdCat.Value);
        }
        #endregion

        #region 分页
        protected void HlHome_Click(object sender, EventArgs e)
        {
            var dba = new RDBEngine();
            var spu = HdId.Value;
            ListInv(dba, spu, 0);
        }

        protected void HlPage1_Click(object sender, EventArgs e)
        {
            int max = int.Parse(HlPage1.CommandArgument);
            var dba = new RDBEngine();
            var spu = HdId.Value;
            ListInv(dba, spu, max);
        }

        protected void HlPage2_Click(object sender, EventArgs e)
        {
            int max = int.Parse(HlPage2.CommandArgument);
            var dba = new RDBEngine();
            var spu = HdId.Value;
            ListInv(dba, spu, max);
        }

        protected void HlPage3_Click(object sender, EventArgs e)
        {
            int max = int.Parse(HlPage3.CommandArgument);
            var dba = new RDBEngine();
            var spu = HdId.Value;
            ListInv(dba, spu, max);
        }

        protected void HlLast_Click(object sender, EventArgs e)
        {
            int max = int.Parse(HlLast.CommandArgument);
            var dba = new RDBEngine();
            var spu = HdId.Value;
            ListInv(dba, spu, max);
        }
        #endregion

        public void ListInv(RDBEngine dba, string spu, int page)
        {
            dba.AddTable(DSpuInv.TABLE);
            dba.AddWhere(DSpuInv.SPU_ID, spu);
            dba.AddSort(DSpuInv.CREATE_TIME, false);

            var table = dba.ExecuteSelect();
            int cnt = table.Rows.Count;
            //if (cnt < 1)
            //{
            //    RpVips.DataSource = table;
            //    RpVips.DataBind();
            //    return;
            //}

            // 每页行数
            int RPP = 20;
            int num = (cnt - 1) / RPP;
            int p = page - 1;
            if (p + 2 > num)
            {
                p = num - 2;
            }
            if (p < 0)
            {
                p = 0;
            }

            HlHome.Enabled = num > 0 && page > 0;
            LlPrev.Visible = num > 3 && page > 0;

            HlPage1.CommandArgument = p.ToString();
            HlPage1.ForeColor = p == page ? Color.Red : Color.Blue;
            p += 1;
            HlPage1.Text = p.ToString();

            if (num > 0)
            {
                HlPage2.Visible = true;
                HlPage2.CommandArgument = p.ToString();
                HlPage2.ForeColor = p == page ? Color.Red : Color.Blue;
                p += 1;
                HlPage2.Text = p.ToString();
            }
            else
            {
                HlPage2.Visible = false;
            }

            if (num > 1)
            {
                HlPage3.Visible = true;
                HlPage3.CommandArgument = p.ToString();
                HlPage3.ForeColor = p == page ? Color.Red : Color.Blue;
                p += 1;
                HlPage3.Text = p.ToString();
            }
            else
            {
                HlPage3.Visible = false;
            }

            LlNext.Visible = num > 3 && page < num - 3;
            HlLast.Enabled = page < num;
            HlLast.CommandArgument = num.ToString();
            LlPage.Text = string.Format("第 {0}/{1} 页", page + 1, num + 1);

            PagedDataSource pds = new PagedDataSource();
            pds.DataSource = table.DefaultView;
            pds.AllowPaging = true;//允许分页
            pds.PageSize = RPP;//单页显示项数
            pds.CurrentPageIndex = page;

            RpPoints.DataSource = pds;
            RpPoints.DataBind();
        }

        private void FindSpu(RDBEngine dba, string meta)
        {
            var sql = @"SELECT *
FROM oms_spu a
WHERE a.code = '{0}'
     OR a.hypy = '{0}'
     OR a.name = '{0}'
     OR a.id IN(SELECT
                  t.sku_id
                FROM oms_spu_barcode t
                WHERE t.barcode = '{0}')";

            var dt = dba.ExecuteSelect(string.Format(sql, meta));
            if (dt.Rows.Count < 1)
            {
                return;
            }

            DataRow row = dt.Rows[0];
            HdId.Value = "" + row[DSpu.ID];
            HdCat.Value = "" + row[DSpu.CAT_ID];
            TbCode.Text = "" + row[DSpu.CODE];
            LlName.Text = "" + row[DSpu.NAME];
            LlUom.Text = "" + row[DSpu.UOM_ID];
            LlSpec.Text = "" + row[DSpu.SPEC];
            LlMode.Text = "" + row[DSpu.MODE];
            LlUsableInv.Text = "" + row[DSpu.USABLE_INV];
        }

        private void ReadSpu(RDBEngine dba, string spu)
        {
            dba.AddTable(DSpu.TABLE);
            dba.AddWhere(DSpu.ID, spu);
            var dt = dba.ExecuteSelect();
            if (dt.Rows.Count != 1)
            {
                return;
            }

            DataRow row = dt.Rows[0];
            HdId.Value = spu;
            HdCat.Value = "" + row[DSpu.CAT_ID];
            TbCode.Text = "" + row[DSpu.CODE];
            LlName.Text = "" + row[DSpu.NAME];
            LlUom.Text = "" + row[DSpu.UOM_ID];
            LlSpec.Text = "" + row[DSpu.SPEC];
            LlMode.Text = "" + row[DSpu.MODE];
            LlUsableInv.Text = "" + row[DSpu.USABLE_INV];
        }

        private void SaveSpu(RDBEngine dba)
        {
            LlErr.Text = "";

            var id = HdId.Value;
            if (!CharUtil.IsValidateHash(id))
            {
                return;
            }

            var adjust = TbAdjust.Text;
            if (string.IsNullOrWhiteSpace(adjust))
            {
                LlErr.Text = "请输入调整数量！";
                return;
            }
            if (!Regex.IsMatch(adjust, "^[-+]?\\d+$"))
            {
                LlErr.Text = "调整数量输入格式错误！";
                return;
            }
            var cnt = int.Parse(adjust);
            if (cnt == 0)
            {
                return;
            }

            var user = WebUtil.CurrentUser(Session);

            dba.AddTable(DSpu.TABLE);
            if (cnt > 0)
            {
                dba.AddParam(DSpu.USABLE_INV, DSpu.USABLE_INV + "+" + cnt, false);
            }
            else
            {
                dba.AddParam(DSpu.USABLE_INV, DSpu.USABLE_INV + cnt, false);
            }
            dba.AddParam(DSpu.UPDATE_TIME, DSpu.NOW, false);
            dba.AddParam(DSpu.UPDATE_USER, user.UserId);
            dba.AddWhere(DSpu.ID, id);
            dba.AddUpdateBatch();

            dba.Reset();

            dba.AddTable(DSpuInv.TABLE);
            dba.AddParam(DSpuInv.ID, HashUtil.UtcTimeInHex());
            dba.AddParam(DSpuInv.SPU_ID, id);
            dba.AddParam(DSpuInv.INV, cnt);
            dba.AddParam(DSpuInv.SOURCE, CSpuInv.SOURCE_MANURE.ToString());
            dba.AddParam(DSpuInv.CREATE_TIME, DSpu.NOW, false);
            dba.AddParam(DSpuInv.CREATE_USER, user.UserId);
            dba.AddInsertBatch();

            dba.ExecuteBatch();

            var tmp = int.Parse(LlUsableInv.Text);
            LlUsableInv.Text = (cnt + tmp).ToString();
        }

        private void ShowDef()
        {
            HdId.Value = "";
            TbCode.Text = "";
            LlName.Text = "";
            LlUom.Text = "";
            LlSpec.Text = "";
            LlMode.Text = "";
            LlUsableInv.Text = "0";
        }
    }
}